package com.lvmama.task.job.common;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * Created by IntelliJ IDEA.<p/>
 * User: troy-kou<p/>
 * Date: 16/1/27<p/>
 * Time: 下午2:44<p/>
 * Email:kouhongyu@163.com<p/>
 */
public class ContextFactory {

    static ContextFactory contextFactory;
    private ConcurrentMap<String, ClassPathXmlApplicationContext> contextMap = new ConcurrentHashMap<String, ClassPathXmlApplicationContext>();
    static Object LOCK1 = new Object();
    static Object LOCK2 = new Object();
    static Object LOCK3 = new Object();

    private ContextFactory() {

    }

    public static ContextFactory getInstance() {
        synchronized (LOCK1) {
            if (contextFactory == null) {
                contextFactory = new ContextFactory();
            }
        }
        return contextFactory;
    }

    public void putContext(String contextName) {
        synchronized (LOCK2) {
            ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(contextName);
            contextMap.put(contextName, context);
        }
    }
    public void removeContext(String contextName) {
        synchronized (LOCK3) {
            contextMap.remove(contextName);
        }
    }

    public ClassPathXmlApplicationContext getContext(String contextName) {
        return contextMap.get(contextName);
    }
}
